package com.eyealike.client.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * A very simple resource pool with no explicit limit on the number of resources
 * acquired by the client at any point in time. The maximum number of free
 * resources that are kept in the pool is configurable.
 */
public abstract class ResourcePool<T>
{
	abstract protected T allocate();

	abstract protected void deallocate( T resource );

	private final BlockingQueue<T> free;

	public ResourcePool( int maxFree )
	{
		free = new ArrayBlockingQueue<T>( maxFree, false );
	}

	public T acquire()
	{
		final T resource = free.poll();
		return resource != null ? resource : allocate();
	}

	public void release( T resource )
	{
		if( ! free.offer( resource ) ) {
			deallocate( resource );
		}
	}
}
